module RBPM
  module Execute
    def auto_run(node, parameters = {})
      case node.class.name
        when 'RBPM::ExclusiveGateway'
          sf = node.which_can_go(parameters)
          node.active.update_attributes status: 0, end_date: Time.now, bpmn_next_target_ref: sf.targetRef
          auto_run node.next(sf), parameters
        when 'RBPM::ParallelGateway'
          parallel_gateway_transaction node, parameters
        when 'RBPM::SequenceFlow'
          auto_run node.next, parameters
        when 'RBPM::ServiceTask'
          node.active.finish! parameters
        when 'RBPM::UserTask'
          user_task_transaction node, parameters
        when 'RBPM::Event'
          if node.node_name == 'endEvent'
            node.engine_finish!
          else
            auto_run node.next, parameters
          end
        else
          # auto_run task_transaction node, parameters
      end
    end

    # 用户任务事务
    def user_task_transaction(node, parameters)
      # 初始化流程变量
      @parameters ||={}
      @parameters = @parameters.merge(parameters)

      user_id, assignee_type = eval(node.assignRule) if defined? node.assignRule
      user_id, assignee_type = 0, 3 if user_id.nil? # 如果用户id没指定，则表示该任务可以被所有人接受
      assignee_type = 0 if assignee_type.nil? #
      @user_task = create_user_task(node, user_id, assignee_type)
    end

    # 并行网关事务
    def parallel_gateway_transaction(node, parameters)
      if node.tasks_finished?
        # 执行之后本活动结束
        node.active.update_attributes status: 0, end_date: Time.now
        node.the_next_flows(node.id).each do |flow|
          auto_run flow, parameters
        end
      end
    end


    # 创建用户任务
    def create_user_task(node, user_id, assignee_type)

      # 如果用户task已经存在
      if node.active.status!=0
        task=nil
        node.active.transaction do
          task = ProcessTask.create process_instance_id: node.process_instance.id, status: 1, assignee_id: user_id,
                                    process_active_instance_id: node.active.id, bpmn_name: node.name, start_at: Time.now,
                                    assignee_type: assignee_type, bpmn_define_id: node.active.bpmn_active_define_id

          node.active.update_attributes current_task_id: task.id, assignee: user_id
        end
        task
      else
        node.active.current_task
      end
    end
  end
end